#!/usr /bin/env python
# -*- coding: utf-8 -*-

import shelve
import paho.mqtt.client as mqtt

from datetime import datetime
from flask import Flask, request, render_template, redirect

application = Flask(__name__)
DATA_FILE = 'i_database.dat'


def save_data(name, comment, time_now):

    database = shelve.open(DATA_FILE)

    if 'msg' not in database:
        msg_list = []
    else:
        msg_list = database['msg']

    msg_list.insert(
        0, {'name': name, 'comment': comment, 'time': time_now})

    database['msg'] = msg_list

    database.close()

def clear_data():
    database = shelve.open(DATA_FILE)
    if 'msg' in database:
        del database['msg'] 

#根据名称修改
def update_data(name,conmment,time_now):
    database = shelve.open(DATA_FILE)
    if 'msg' in database:
        msg_db = database['msg']
        for msg in msg_db:
            if msg.name == name:
               msg.conmment = conmment
               msg.time_now = time_now
               database['msg'] = msg_db


def load_data():
    database = shelve.open(DATA_FILE)
    msg = database.get('msg', [])
    database.close()
    return msg


@application.route('/')
def index():
    msg = load_data()
    return render_template('index.html', msg=msg)

@application.route('/clear')
def clear():
    clear_data()
    return redirect('/')

@application.route('/post_save', methods=['POST'])
def post_save():
    name = request.form.get('name')
    comment = request.form.get('comment')
    time_now = datetime.now().replace(microsecond=0)

    save_data(name, comment, time_now)
    #重定向
    return redirect('/')

# mqtt app

MQTTHOST = "192.168.1.2"
MQTTPORT = 1883
mqttClient = mqtt.Client()
mqtt_msg_list = []

def on_message_come(lient, userdata, msg):
    mqtt_msg_list.insert(
        0, {'topic': msg.topic, 'comment':str(msg.payload)})
  
@application.route('/mqtt')
def mqtt_init():
    mqtt_msg_list = []
    mqttClient.connect(MQTTHOST, MQTTPORT, 60)
    mqttClient.loop_start()
    mqttClient.subscribe("application/#", 1)
    mqttClient.on_message = on_message_come # 消息到来处理函数
    
    return redirect('/mqtt_start')

@application.route('/mqtt_start',methods=['GET','POST'])
def mqtt_show():
    global mqtt_msg
    if request.method == 'GET':
        return render_template('mqtt.html',mqtt_msg_list = mqtt_msg_list)
    else:
        return render_template('mqtt.html',mqtt_msg_list = mqtt_msg_list)


if __name__ == '__main__':
    application.run('0.0.0.0', port=5000, debug=True)

